package edu.zjut.hjg.saas.web.controller.admin;

import static edu.zjut.hjg.saas.web.support.SaaSConstants.SESSION_NAME_ADMIN;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import edu.zjut.hjg.saas.biz.model.Admin;
import edu.zjut.hjg.saas.biz.service.AdminService;
import edu.zjut.hjg.saas.common.annotation.CookieSessionOut;
import edu.zjut.hjg.saas.web.model.AdminSession;

/**
 * 管理员登录
 *
 * @author hjg
 */
@Controller("adminLoginController")
public class LoginController {

    @Autowired
    private AdminService adminService;

    @CookieSessionOut(SESSION_NAME_ADMIN)
    @RequestMapping("/adminDoLogin.htm")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password, Model model) {
        Admin admin = adminService.authenticate(username, password);
        if (admin == null) {
            model.addAttribute("username", username);
            model.addAttribute("msgCode", "error.login.failed");
            return "admin/login";
        }
        AdminSession adminSession = new AdminSession();
        adminSession.setId(admin.getId());
        adminSession.setName(admin.getName());
        adminSession.setUsername(admin.getUsername());
        model.addAttribute(SESSION_NAME_ADMIN, adminSession);
        return "redirect:/admin/index.htm";
    }

    @RequestMapping("/adminLogout.htm")
    @CookieSessionOut(SESSION_NAME_ADMIN)
    public String logout(Model model) {
        model.addAttribute(SESSION_NAME_ADMIN, null);
        return "redirect:/adminLogin.htm";
    }
}
